import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { NavBar, Tabs, Empty, DotLoading, PullToRefresh, InfiniteScroll } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import axios from '../../api/http'

type DrugOrder = {
  id: string | number
  status: 'pendingPay' | 'pendingShip' | 'pendingReceive' | 'pendingPickup' | 'done' | 'closed'
  title?: string
  createdAt?: string
}

const tabDefs = [
  { key: 'all', title: '全部' },
  { key: 'pendingPay', title: '待付款' },
  { key: 'pendingShip', title: '待发货' },
  { key: 'pendingReceive', title: '待收货' },
  { key: 'pendingPickup', title: '待自取' },
  { key: 'done', title: '已完成' }
] as const

function Index() {
  const nav = useNavigate()
  const [active, setActive] = useState<typeof tabDefs[number]['key']>('all')
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState<DrugOrder[]>([])
  const [pageCode, setPageCode] = useState(1)
  const pageSize = 10
  const [hasMore, setHasMore] = useState(true)
  const [refreshing, setRefreshing] = useState(false)

  const serverStatus = useMemo(() => (active === 'all' ? undefined : active), [active])

  const fetchPage = useCallback(async (page:number) => {
    const params:any = { pageCode: page, pageSize }
    if (serverStatus) params.status = serverStatus
    // 真实接口请替换为你的用药建议/订单列表 API
    const res:any = await axios.get('/drug/order/list', { params })
    const items:DrugOrder[] = (res && (res.data || res.list)) || []
    return Array.isArray(items) ? items : []
  }, [serverStatus])

  useEffect(() => {
    setLoading(true)
    setHasMore(true)
    setPageCode(1)
    fetchPage(1).then(first => {
      setList(first)
      setHasMore(first.length === pageSize)
    }).finally(()=> setLoading(false))
  }, [fetchPage, pageSize])

  const loadMore = useCallback(async () => {
    if (!hasMore) return
    const nextPage = pageCode + 1
    const next = await fetchPage(nextPage)
    setList(prev => [...prev, ...next])
    setPageCode(nextPage)
    setHasMore(next.length === pageSize)
  }, [fetchPage, hasMore, pageCode, pageSize])

  const onRefresh = useCallback(async () => {
    setRefreshing(true)
    const fresh = await fetchPage(1)
    setList(fresh)
    setPageCode(1)
    setHasMore(fresh.length === pageSize)
    setRefreshing(false)
  }, [fetchPage, pageSize])

  return (
    <div style={{background:'#fff', minHeight:'100vh'}}>
      <NavBar onBack={() => nav(-1)}>用药建议</NavBar>

      <Tabs activeKey={active} onChange={(k)=>setActive(k as any)}>
        {tabDefs.map(t => (
          <Tabs.Tab key={t.key} title={t.title} />
        ))}
      </Tabs>

      {loading ? (
        <div style={{display:'flex',alignItems:'center',justifyContent:'center',padding:'40px 0'}}>
          <DotLoading />
          <span style={{marginLeft:8, color:'#999'}}>加载中...</span>
        </div>
      ) : list.length === 0 ? (
        <div style={{paddingTop:'14vh'}}>
          <Empty description='暂无数据' />
        </div>
      ) : (
        <PullToRefresh onRefresh={onRefresh} refreshing={refreshing}>
          <div style={{padding:'0 12px'}}>
            {list.map(item => (
              <div key={item.id} style={{padding:'12px 0', borderBottom:'1px solid #f2f2f2'}}>
                <div style={{fontSize:15, fontWeight:600}}>{item.title || '用药单'}</div>
                <div style={{marginTop:6, fontSize:12, color:'#888'}}>{item.createdAt || ''}</div>
              </div>
            ))}
            <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
          </div>
        </PullToRefresh>
      )}
    </div>
  )
}

export default Index
